package com.riche.contractbackend.config;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * @ClassName: RedisTemplateConfig
 * @Description: 自定义Redis配置类
 * @Author: Gaoruiqi
 * @Date: 2025-09-08 10:51
 * @Version: 1.0
 **/

/*
@Configuration
@EnableRedisHttpSession  // 启用Redis存储Session
public class RedisTemplateConfig {

    // 定义全局通用的JSON序列化器（带类型信息）
    private GenericJackson2JsonRedisSerializer getJsonSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 关键：添加类型信息，支持反序列化时识别具体类（解决之前的User类识别问题）
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,  // 对非final类添加类型信息
                JsonTypeInfo.As.PROPERTY  // 类型信息以@class字段存储在JSON中
        );
        // 支持LocalDateTime等Java 8日期类型
        objectMapper.registerModule(new JavaTimeModule());
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    // 配置Spring Session专用的序列化器（与通用序列化器保持一致）
    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return getJsonSerializer();
    }

    // 配置通用RedisTemplate（与Spring Session共享同一序列化器）
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 统一设置序列化器
        RedisSerializer<String> stringSerializer = RedisSerializer.string();  // Key用String序列化
        GenericJackson2JsonRedisSerializer jsonSerializer = getJsonSerializer();  // Value用JSON序列化

        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(jsonSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);  // Hash结构的Key也用String
        redisTemplate.setHashValueSerializer(jsonSerializer);  // Hash结构的Value也用JSON

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
*/
